<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>桌宠设置</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 600px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }

        h1 {
            color: #667eea;
            margin-bottom: 10px;
            font-size: 28px;
        }

        .subtitle {
            color: #999;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .section {
            margin-bottom: 30px;
        }

        .section h2 {
            font-size: 18px;
            margin-bottom: 15px;
            color: #555;
            border-bottom: 2px solid #667eea;
            padding-bottom: 8px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #555;
        }

        input[type="file"],
        input[type="number"],
        input[type="range"] {
            width: 100%;
            padding: 10px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        input[type="file"]:focus,
        input[type="number"]:focus {
            outline: none;
            border-color: #667eea;
        }

        input[type="range"] {
            padding: 0;
        }

        .range-value {
            display: inline-block;
            margin-left: 10px;
            font-weight: bold;
            color: #667eea;
        }

        .checkbox-group {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }

        input[type="checkbox"] {
            width: 20px;
            height: 20px;
            margin-right: 10px;
            cursor: pointer;
        }

        .btn-group {
            display: flex;
            gap: 10px;
            margin-top: 30px;
        }

        button {
            flex: 1;
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: #f0f0f0;
            color: #555;
        }

        .btn-secondary:hover {
            background: #e0e0e0;
        }

        .preview {
            width: 100px;
            height: 100px;
            border: 2px dashed #ccc;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 10px;
            overflow: hidden;
        }

        .preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        .help-text {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }

        .tab-btn {
            transition: all 0.3s ease;
        }

        .tab-btn:hover {
            opacity: 0.8;
        }

        .tab-btn.active {
            background: #667eea !important;
            color: white !important;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🐱 桌宠设置</h1>
        <p class="subtitle">自定义你的桌面宠物</p>

        <!-- 外观设置 -->
        <div class="section">
            <h2>外观设置</h2>
            
            <div class="form-group">
                <label for="petImage">桌宠图片</label>
                
                <!-- 选项卡切换 -->
                <div style="display: flex; gap: 10px; margin-bottom: 10px;">
                    <button type="button" id="localTab" class="tab-btn active" style="flex: 1; padding: 8px; border: 2px solid #667eea; background: #667eea; color: white; border-radius: 6px; cursor: pointer; font-weight: 600;">
                        本地文件
                    </button>
                    <button type="button" id="urlTab" class="tab-btn" style="flex: 1; padding: 8px; border: 2px solid #667eea; background: white; color: #667eea; border-radius: 6px; cursor: pointer; font-weight: 600;">
                        URL 链接
                    </button>
                </div>
                
                <!-- 本地文件选择 -->
                <div id="localInput">
                    <input type="file" id="petImage" accept="image/*">
                    <p class="help-text">支持 PNG, JPG, GIF, SVG 格式</p>
                </div>
                
                <!-- URL 输入 -->
                <div id="urlInput" style="display: none;">
                    <input type="text" id="petImageUrl" placeholder="https://example.com/image.png" style="width: 100%; padding: 10px; border: 2px solid #e0e0e0; border-radius: 6px; font-size: 14px;">
                    <p class="help-text">输入图片的完整 URL 地址（支持 PNG, JPG, GIF, SVG）</p>
                    <button type="button" id="loadUrlBtn" style="margin-top: 10px; padding: 8px 16px; background: #667eea; color: white; border: none; border-radius: 6px; cursor: pointer;">
                        加载预览
                    </button>
                </div>
                
                <div class="preview" id="preview">
                    <span style="color: #ccc;">预览</span>
                </div>
            </div>

            <div class="form-group">
                <label for="petSize">桌宠大小: <span class="range-value" id="sizeValue">100</span>px</label>
                <input type="range" id="petSize" min="50" max="300" value="100">
            </div>
        </div>

        <!-- 行为设置 -->
        <div class="section">
            <h2>行为设置</h2>
            
            <div class="form-group">
                <label for="petSpeed">移动速度: <span class="range-value" id="speedValue">2</span></label>
                <input type="range" id="petSpeed" min="1" max="10" value="2">
            </div>

            <div class="checkbox-group">
                <input type="checkbox" id="autoMove" checked>
                <label for="autoMove">自动移动</label>
            </div>

            <div class="checkbox-group">
                <input type="checkbox" id="dragEnabled" checked>
                <label for="dragEnabled">允许拖动</label>
            </div>

            <div class="checkbox-group">
                <input type="checkbox" id="alwaysOnTop" checked>
                <label for="alwaysOnTop">始终置顶</label>
            </div>
        </div>

        <!-- 按钮组 -->
        <div class="btn-group">
            <button class="btn-secondary" id="resetBtn">恢复默认</button>
            <button class="btn-primary" id="saveBtn">保存设置</button>
        </div>
    </div>

    <script>
        const { ipcRenderer } = require('electron');
        const fs = require('fs');
        const path = require('path');
        const https = require('https');
        const http = require('http');

        // 加载配置
        let config = {};
        try {
            const configPath = path.join(__dirname, 'config.json');
            config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
        } catch (error) {
            console.error('加载配置失败:', error);
        }

        // 图片来源类型
        let imageSource = 'local'; // 'local' 或 'url'
        let currentImageUrl = '';

        // 初始化表单值
        document.getElementById('petSize').value = config.pet?.size || 100;
        document.getElementById('sizeValue').textContent = config.pet?.size || 100;
        document.getElementById('petSpeed').value = config.pet?.speed || 2;
        document.getElementById('speedValue').textContent = config.pet?.speed || 2;
        document.getElementById('autoMove').checked = config.behavior?.autoMove !== false;
        document.getElementById('dragEnabled').checked = config.behavior?.dragEnabled !== false;
        document.getElementById('alwaysOnTop').checked = config.window?.alwaysOnTop !== false;

        // 预览当前图片
        if (config.pet?.imagePath) {
            const imgPath = path.join(__dirname, config.pet.imagePath);
            if (fs.existsSync(imgPath)) {
                const preview = document.getElementById('preview');
                preview.innerHTML = `<img src="${imgPath}" alt="桌宠预览">`;
            }
        }

        // 范围滑块更新
        document.getElementById('petSize').addEventListener('input', (e) => {
            document.getElementById('sizeValue').textContent = e.target.value;
        });

        document.getElementById('petSpeed').addEventListener('input', (e) => {
            document.getElementById('speedValue').textContent = e.target.value;
        });

        // 选项卡切换
        document.getElementById('localTab').addEventListener('click', () => {
            imageSource = 'local';
            document.getElementById('localTab').classList.add('active');
            document.getElementById('urlTab').classList.remove('active');
            document.getElementById('localInput').style.display = 'block';
            document.getElementById('urlInput').style.display = 'none';
        });

        document.getElementById('urlTab').addEventListener('click', () => {
            imageSource = 'url';
            document.getElementById('urlTab').classList.add('active');
            document.getElementById('localTab').classList.remove('active');
            document.getElementById('urlInput').style.display = 'block';
            document.getElementById('localInput').style.display = 'none';
        });

        // 图片预览（本地文件）
        document.getElementById('petImage').addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    const preview = document.getElementById('preview');
                    preview.innerHTML = `<img src="${event.target.result}" alt="桌宠预览">`;
                };
                reader.readAsDataURL(file);
            }
        });

        // URL 图片加载预览
        document.getElementById('loadUrlBtn').addEventListener('click', () => {
            const url = document.getElementById('petImageUrl').value.trim();
            if (!url) {
                alert('请输入图片 URL');
                return;
            }

            // 验证 URL 格式
            try {
                new URL(url);
            } catch (e) {
                alert('URL 格式不正确，请输入完整的图片地址');
                return;
            }

            // 直接预览 URL 图片
            const preview = document.getElementById('preview');
            preview.innerHTML = `<img src="${url}" alt="桌宠预览" onerror="this.parentElement.innerHTML='<span style=\\'color: red;\\'>图片加载失败</span>'">`;
            currentImageUrl = url;
        });

        // 保存设置
        document.getElementById('saveBtn').addEventListener('click', () => {
            const fileInput = document.getElementById('petImage');
            const newConfig = {
                pet: {
                    imagePath: config.pet?.imagePath || './assets/default-pet.svg',
                    imageUrl: config.pet?.imageUrl || '',
                    size: parseInt(document.getElementById('petSize').value),
                    speed: parseInt(document.getElementById('petSpeed').value),
                    useUrl: imageSource === 'url'
                },
                window: {
                    alwaysOnTop: document.getElementById('alwaysOnTop').checked,
                    showInTaskbar: false
                },
                behavior: {
                    autoMove: document.getElementById('autoMove').checked,
                    dragEnabled: document.getElementById('dragEnabled').checked
                }
            };

            // 如果使用 URL
            if (imageSource === 'url') {
                const url = document.getElementById('petImageUrl').value.trim();
                if (!url) {
                    alert('请输入图片 URL 或切换到本地文件');
                    return;
                }
                
                try {
                    new URL(url);
                    newConfig.pet.imageUrl = url;
                } catch (e) {
                    alert('URL 格式不正确');
                    return;
                }
            }
            // 如果选择了本地文件
            else if (fileInput.files.length > 0) {
                const file = fileInput.files[0];
                const fileName = `custom-pet${path.extname(file.name)}`;
                const targetPath = path.join(__dirname, 'assets', fileName);
                
                try {
                    fs.copyFileSync(file.path, targetPath);
                    newConfig.pet.imagePath = `./assets/${fileName}`;
                } catch (error) {
                    alert('文件保存失败：' + error.message);
                    return;
                }
            }

            // 保存配置文件
            try {
                const configPath = path.join(__dirname, 'config.json');
                fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2));
                
                // 通知主进程配置已更新
                ipcRenderer.send('config-updated', newConfig);
                
                alert('设置已保存！请重启应用以应用更改。');
            } catch (error) {
                alert('保存失败：' + error.message);
            }
        });

        // 恢复默认
        document.getElementById('resetBtn').addEventListener('click', () => {
            if (confirm('确定要恢复默认设置吗？这将恢复默认图片和所有设置。')) {
                // 恢复默认值
                document.getElementById('petSize').value = 100;
                document.getElementById('sizeValue').textContent = 100;
                document.getElementById('petSpeed').value = 2;
                document.getElementById('speedValue').textContent = 2;
                document.getElementById('autoMove').checked = true;
                document.getElementById('dragEnabled').checked = true;
                document.getElementById('alwaysOnTop').checked = true;
                document.getElementById('petImage').value = '';
                document.getElementById('petImageUrl').value = '';
                
                // 切换到本地文件选项卡
                imageSource = 'local';
                document.getElementById('localTab').classList.add('active');
                document.getElementById('urlTab').classList.remove('active');
                document.getElementById('localInput').style.display = 'block';
                document.getElementById('urlInput').style.display = 'none';
                
                // 显示默认图片预览
                const preview = document.getElementById('preview');
                const defaultImagePath = path.join(__dirname, 'assets', 'default-pet.svg');
                preview.innerHTML = `<img src="${defaultImagePath}" alt="默认桌宠">`;
                
                // 立即保存默认配置
                const defaultConfig = {
                    pet: {
                        imagePath: './assets/default-pet.svg',
                        imageUrl: '',
                        useUrl: false,
                        size: 100,
                        speed: 2
                    },
                    window: {
                        alwaysOnTop: true,
                        showInTaskbar: false
                    },
                    behavior: {
                        autoMove: true,
                        dragEnabled: true
                    }
                };
                
                try {
                    const configPath = path.join(__dirname, 'config.json');
                    fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2));
                    
                    // 通知主进程配置已更新
                    ipcRenderer.send('config-updated', defaultConfig);
                    
                    alert('已恢复默认设置！请重启应用以应用更改。');
                } catch (error) {
                    alert('恢复默认设置失败：' + error.message);
                }
            }
        });
    </script>
</body>
</html>

